# coding=utf-8
# ☯ Author: ChinaPython
# ☯ Email : chinapython@yeah.net
# ☯ Date  : 2019-10-21
import cv2
import time
import numpy as np
from PIL import Image


class BigShears:
    def __init__(self):
        pass

    @staticmethod
    def cut_chart(path, sts):
        img = cv2.imread(path)
        mask = np.zeros(img.shape, np.uint8)
        pts = np.array([sts], np.int32).reshape((-1, 1, 2))
        mask = cv2.polylines(mask, [pts], True, (0, 0, 0))
        cv2.fillPoly(mask, [pts], (255, 255, 255))
        masked = cv2.bitwise_and(mask, img)
        Image.fromarray(img)
        array = np.zeros((masked.shape[0], masked.shape[1], 4), np.uint8)
        array[:, :, 0:3] = masked
        array[:, :, 3] = 0
        array[:, :, 3][np.where(array[:, :, 0] > 2)] = 255
        array[:, :, 3][np.where(array[:, :, 1] > 2)] = 255
        array[:, :, 3][np.where(array[:, :, 2] > 2)] = 255
        image = Image.fromarray(array).crop((
            min([x for (x, _) in sts]),
            min([y for (_, y) in sts]),
            max([x for (x, _) in sts]),
            max([y for (_, y) in sts]))
        )
        image.putdata([(255, 255, 255, 0) if item[:3] == (255, 255, 255) else item for item in image.getdata()])
        image.save("sad.png")


if __name__ == '__main__':
    start = BigShears()
    coordinates = [(135, 686), (136, 1234), (823, 1236), (823, 1171), (594, 1046), (591, 687)]
    start.cut_chart('static/image/test.png', coordinates)

